package engine.BIEngine0_1;

import java.io.IOException;
import java.util.List;

import beans.FullJobState;
import beans.HttpConfig;
import beans.HttpResult;
import beans.HttpResultList;
import dao.HistoryTaskDao;
import dao.JobDao;
import net.sf.json.JSONObject;
import utils.Log4jInit;
import utils.Time2Str;

public class InitJobStateThread extends Thread {
    private String batchTaskHash;
    private HistoryTaskDao historyTaskDao;
    private JobDao jobDao;

    public InitJobStateThread(String batchTaskHash) {
        this.batchTaskHash = batchTaskHash;
        this.historyTaskDao = new HistoryTaskDao();
        this.jobDao = new JobDao();
    }

    //任务启动后，更新作业部分信息
    @Override
    public void run() {
        /**
         * 从服务器获取token
         */
        HttpResult tokenResult = AlgorithmOperator.getToken(HttpConfig.userName, HttpConfig.passWord);
        if(tokenResult.isResult()){
            String token = tokenResult.getMessage();
            List<Object> subTaskHashList = historyTaskDao.getSubTaskHashByBatchTaskHash(batchTaskHash).getDatas();
            for(Object subTaskHash:subTaskHashList){
                Log4jInit.logger.info(""+subTaskHash);
                List<Object> jobIdList;
                //任务启动成功后，可能子任务线程还未执行完，即还未往history_job插入作业数据，
                while (true){
                    jobIdList = jobDao.getJobIdByTaskHash((String)subTaskHash);
                    if(jobIdList.size()>=1){
                        break;
                    }
                }
                Log4jInit.logger.info(""+jobIdList);
                for(Object jobId:jobIdList){
                    HttpResultList result = null;
                    try {
                        result = AlgorithmOperator.getJobFullState((String)jobId, token);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    FullJobState fullJobState = (FullJobState)result.getDatas().get(0);
                    jobDao.updateJobNameAndFullInfo(fullJobState.getJobName(),JSONObject.fromObject(fullJobState).toString(),(String)jobId);
                }
            }
        }
        //Time2Str.printCurrentTime("IniJobStateThread");
    }
}